// eslint-disable-next-line @typescript-eslint/no-var-requires
const fs = require('fs');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const path = require('path');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const baseUrl = path.join(__dirname, '../');

const getPackages = function (root) {
  const currentRoot = path.join(__dirname, '..', root);
  return fs
    .readdirSync(currentRoot)
    .map((dirPath) => {
      try {
        const pkg = JSON.parse(fs.readFileSync(path.join(currentRoot, dirPath, 'package.json'), 'utf-8'));
        return pkg.name;
      } catch (e) {
        return false;
      }
    })
    .filter((i) => !!i);
};
const allPackages = getPackages('packages');
const regList = [
  ...allPackages.map((pkg) => {
    pkg = pkg.replace(new RegExp(`\\${path.sep}`, 'g'), `\\${path.sep}`);
    return new RegExp(`${pkg}\\${path.sep}.*\\.module\\.scss$`);
  }),
  /pages[\\/].*\.module\.scss$/,
];

module.exports = {
  devtool: 'cheap-module-source-map',
  mode: process.env.NODE_ENV || 'development',
  node: {
    fs: 'empty',
  },
  entry: fs.readdirSync(path.join(baseUrl, './src')).reduce((entries, dir) => {
    const fullDir = path.join(baseUrl, 'src', dir);
    const entry = path.join(fullDir, 'index.ts');
    // 排除api声明包
    if (fs.statSync(fullDir).isDirectory() && fs.existsSync(entry)) {
      if (fullDir.includes('src/pages'.split('/').join(path.sep))) {
        entries[dir] = ['webpack-hot-middleware/client?reload=true', entry];
      } else {
        entries[dir] = entry;
      }
    }

    return entries;
  }, {}),

  output: {
    globalObject: 'this',
    path: path.join(__dirname, '__build__'),
    filename: '[name].js',
    chunkFilename: '[id].chunk.js',
    publicPath: '/__build__/',
  },

  module: {
    rules: [
      /*{
                test: /node_modules\/(moment.*|@qunhe\/protobuf-.*|@?protobufjs.*|@qunhe\/pixi.js*|@qunhe\/tools-ui*|@qunhe\/tools-components*|@qunhe\/inference-engine-2d*)/,
                use: 'null-loader',
            },*/
      {
        exclude: /node_modules/,
        test: /\.tsx?$/,
        use: [
          'cache-loader',
          {
            loader: 'babel-loader',
            options: {
              rootMode: 'upward',
            },
          },
          {
            loader: 'ts-loader',
            options: {
              allowTsInNodeModules: true,
              happyPackMode: true,
              transpileOnly: true,
            },
          },
        ],
      },
      {
        test: /\.drcwasm$/,
        loaders: ['arraybuffer-loader'],
      },
      {
        test: [/\.svg$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
        use: [
          {
            loader: 'file-loader',
          },
        ],
      },
      //{ test: /\.css$/, use: [ 'cache-loader', 'style-loader', 'css-loader'] },
      {
        test: /\.s?[ac]ss$/i,
        use: [
          {
            loader: 'style-loader',
          },
          // Translates CSS into CommonJS
          {
            loader: 'css-loader',
            options: {
              modules: false,
              camelCase: true,
              localIdentName: '[local]_[hash:base64:5]',
            },
          },
          {
            loader: 'postcss-loader',
            options: {
              // Necessary for external CSS imports to work
              // https://github.com/facebookincubator/create-react-app/issues/2677
              ident: 'postcss',
              plugins: () => [require('postcss-flexbugs-fixes'), require('autoprefixer')],
            },
          },
          // Compiles Sass to CSS
          {
            loader: 'sass-loader',
            options: {
              /*additionalData: (content, { resourcePath }) => {
                                if (allPackages.some((it) => resourcePath.includes(it))) {
                                    return `@import "@qunhe/miniapp-model-viewer-component/scss/index.scss";
                                    ${content}
                                `;
                                }
                                return content;
                            },*/
            },
          },
        ],
        exclude: (filePath) => {
          return regList.some((reg) => reg.test(filePath));
        },
      },
      {
        test: (filePath) => {
          return regList.some((reg) => reg.test(filePath));
        },
        use: [
          // Creates `style` nodes from JS strings
          {
            loader: 'style-loader',
          },
          // Translates CSS into CommonJS
          {
            loader: 'css-loader',
            options: {
              modules: true,
              camelCase: true,
              localIdentName: '[local]_[hash:base64:5]',
            },
          },
          {
            loader: 'postcss-loader',
            options: {
              // Necessary for external CSS imports to work
              // https://github.com/facebookincubator/create-react-app/issues/2677
              ident: 'postcss',
              plugins: () => [require('postcss-flexbugs-fixes'), require('autoprefixer')],
            },
          },
          // Compiles Sass to CSS
          {
            loader: 'sass-loader',
            options: {
              /*additionalData: (content, { resourcePath }) => {
                                if (allPackages.some((it) => resourcePath.includes(it))) {
                                    return `@import "@qunhe/miniapp-model-viewer-component/scss/index.scss";
                                    ${content}
                                `;
                                }
                                return content;
                            },*/
            },
          },
        ],
      },
      {
        test: /\.js$/,
        exclude: /node_modules(\/|\\)(?!@qunhe.(rc-components))/,
        use: ['cache-loader', 'babel-loader'],
      },
    ],
  },
  resolve: {
    alias: {},
    // Add `.ts` and `.tsx` as a resolvable extension.
    extensions: ['.js', '.jsx', '.ts', '.tsx', '.vue', '.css', '.scss', '.less', '.json'],
  },

  optimization: {
    /*splitChunks: {
            cacheGroups: {
                vendors: {
                    name: 'shared',
                    filename: 'shared.js',
                    chunks: 'initial',
                },
            },
        },*/
  },

  plugins: [
    new webpack.DefinePlugin({
      CONFIG: {
        productId: process.env.NODE_ENV === 'development' ? '"3FO4GQYLLPHC"' : '"3FO489BAK7UJ"',
      },
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
  ],
};
